#coding=<utf-8>
class ManagedCode(object):
	def __init__(self):
		self.procName = ""
		self.dllimp = ""
		self.dllImpLine = ""
		self.retLine = "" 
		self.procBodyLine = ""

	def outputDeclare(self):
		return self.dllImpLine + self.retLine + self.procBodyLine.replace("public ", "")

	def outputDelegate(self):
		str = "[UnmanagedFunctionPointer(CallingConvention.StdCall,CharSet = CharSet.Unicode, SetLastError = true)]\n"
		str += self.procBodyLine.replace("public static extern", "delegate") \
						.replace(self.procName, "D"+self.procName) \
						.replace("[System.Runtime.InteropServices.InAttribute()]", "") 
		return str.strip()
		
	def outputHookedProc(self):

		return self.procBodyLine.replace("public static extern ", "static") \
						.replace(self.procName, self.procName + "_Hooked") \
						.replace("[System.Runtime.InteropServices.InAttribute()]", "") \
						.strip()

	def output(self):
		str = "/*----code generated by script CodeGenerator.py----*/\n"
		str +="/*----"+self.procName+"----*/\n"
		str += self.outputDelegate() + "\n" + self.outputDeclare() +"\n" + self.outputHookedProc() + "\n"
		return str

def stripMisc(str):
	return str.replace("System.Runtime.InteropServices.", "") \
			  .replace("System.", "")	

if __name__ == "__main__":
	flag = False
	with open("D:\\Source\\APIMonitor\\CodeGenerator\\FileApiInput.txt", "r") as ins:
		with open("D:\\Source\\APIMonitor\\CodeGenerator\\FileApiOutput.txt", "w+") as out:
			for line in ins:
				line = line.lstrip()
				if line.startswith('public partial class'):
					#new a managedCode
					m = ManagedCode()
					flag = True
				elif line.startswith("[System.Runtime.InteropServices.DllImportAttribute".lstrip()):
					m.dllImpLine = line
					#get dll and api name from line
					start = 0
					start = line.find('"', start)
					end = line.find('"', start+1)
					m.dllimp = line[start+1 : end]

					start = end+1;
					start = line.find('"', start)
					end = line.find('"', start+1)
					m.procName = line[start+1 : end]
					
				elif line.startswith('[return:'):
					m.retLine = line
				elif line.startswith('public static extern'.lstrip()):
					m.procBodyLine = line
				elif line.startswith('}') and flag:
					out.write(stripMisc(m.output()))
					flag = False